//Cracking the coding interview (5th), 1_4
// Write a method to replace all spaces in a string with '%20'. You mayh assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementating in Java, please use a character array so that you can perform this operation in place.)
// EXAMPLE
// Input: "Mr John Smith     "
// Output: "Mr%20John%20Smith"

#include<string>
#include<iostream>
using namespace std;

int compress_str(string &input, int& len) 
{
  int blank_num = 0;

  for(int i = 0; i < len; i++) {
    if(input[i] == ' ')
      blank_num++;
  }
 
  int last = len-1; 
  while (input[last] == ' ') {
      blank_num--;
      last--;
  }
  len = last + 1;  

  int pos = len + 2 * blank_num;
  if (input.size() < pos)
    return -1;
  
  int i = pos - 1;
  int j = len - 1;

  while (j >= 0) { 
    if(input[j] == ' ') {
      input[i--] = '0';
      input[i--] = '2';
      input[i--] = '%';
      j--;
    } else {
      input[i--] = input[j--];
    }
  }
}

int main(int argc, char *argv[])
{
  int str_len;
  string s1 = "Mr John Smith    ";
  //string s1 = "Mr    John";

  str_len = s1.size();
  s1.resize(200);
  if (compress_str(s1, str_len))
    cout<<"error occurs."<<endl;
  else
    cout<<s1<<endl; 

  return 0;
}
